package com.tenglong.teacher.ui.homeworkNew;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.cuotibao.zhuoxiao.basics.utils.Utils;
import com.netease.nimlib.sdk.msg.attachment.AudioAttachment;
import com.netease.nimlib.sdk.msg.attachment.FileAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.HomeWorkIM;
import com.tenglong.teacher.data.resultInfo.PublishHomeworkResurtInfo;
import com.tenglong.teacher.data.resultInfo.homework.HomeWork;
import com.tenglong.teacher.data.resultInfo.homework.HomeWorkPublishInfo;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.data.resultInfo.homework.HomeWorkStateItem;
import com.tenglong.teacher.data.resultInfo.homework.HomeworkInfo;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.adapter.HomeworkStudentListAdapter;
import com.tenglong.teacher.ui.audio.MediaManager;
import com.tenglong.teacher.ui.common.activity.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeworkStudentListActivity extends BaseActivity implements OnRefreshListener, HomeworkStudentListAdapter.HomeworkStudentListListener {

    public static final String KEY_HOMEWORK_ID = "key_homework_id";
    public static final String KEY_CLASS_ID = "key_class_id";
    public static final String KEY_CLASS_NAME = "key_class_name";
    public static final String KEY_CLASS_TOTAL_STUDENT_NUMBER = "key_class_tatal_student_number";
    private RecyclerView mRecyclerView;
    private TextView complete;
    private List<HomeWork> infos;
    private HomeworkStudentListAdapter mAdapter;
    private String homeworkId;
    private String classId;
    private String className;
    private int studentTotalNumber;
    private int studentSubmitNumber;
    private View noData;
    private SmartRefreshLayout mSmartRefreshLayout;
    private boolean isFirstDownLoad = true;
    private int mClickPosition = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_homework_student_list);
        homeworkId = getIntent().getStringExtra(KEY_HOMEWORK_ID);
        classId= getIntent().getStringExtra(KEY_CLASS_ID);
        className = getIntent().getStringExtra(KEY_CLASS_NAME);
        studentTotalNumber = getIntent().getIntExtra(KEY_CLASS_TOTAL_STUDENT_NUMBER, 0);

        initView();
        initRecy();
        setAdapter();
        setListeners();
        requestData();
    }

    private void setListeners() {
        mSmartRefreshLayout.setEnableLoadMore(false);
        mSmartRefreshLayout.setOnRefreshListener(this);
        mAdapter.setHomeworkStudentListListener(this);
        complete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                homeworkReplacement();
            }
        });
    }
    private void homeworkReplacement(){
        showProgressDialog("补发作业中...");
        CreateRequestEntity.getWebService().homeworkReplacement(homeworkId,classId).enqueue(new Callback<BaseResult<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResult<Boolean>> call, Response<BaseResult<Boolean>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    ToastUtils.showCenterToast("补发作业成功");
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
                dismissProgressDialog();
            }

            @Override
            public void onFailure(Call<BaseResult<Boolean>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
                dismissProgressDialog();
            }
        });
    }
    private void requestData() {
        if (isFirstDownLoad) {
            showProgressDialog("数据加载中...");
            isFirstDownLoad = false;
        }
        CreateRequestEntity.getWebService().queryByClassIdAndHomeworkId(classId,homeworkId).enqueue(new Callback<BaseResult<HomeworkInfo>>() {
            @Override
            public void onResponse(Call<BaseResult<HomeworkInfo>> call, Response<BaseResult<HomeworkInfo>> response) {
                mSmartRefreshLayout.finishRefresh(true);
                if (ResultVerifier.isSucceed(response)) {
                    if (response.body().data != null) {
                        infos.clear();
                        if (response.body().data.homeWork != null && response.body().data.homeWork.size() > 0) {
                            infos.add(getPublishInfo(response.body().data.homeWork, response.body().data.status));
                        }
                        if (response.body().data.studentHWlist != null && response.body().data.studentHWlist.size() > 0) {
                            infos.addAll(response.body().data.studentHWlist);
                            studentSubmitNumber = response.body().data.studentHWlist.size();
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
                noData.setVisibility(infos.size() == 0 ? View.VISIBLE : View.GONE);
                dismissProgressDialog();
            }

            @Override
            public void onFailure(Call<BaseResult<HomeworkInfo>> call, Throwable t) {
                mSmartRefreshLayout.finishRefresh(false);
                ResultVerifier.systerErrers(t);
                noData.setVisibility(infos.size() == 0 ? View.VISIBLE : View.GONE);
                dismissProgressDialog();
            }
        });
    }

    private void setAdapter() {
        infos = new ArrayList<>();
        mAdapter = new HomeworkStudentListAdapter(infos);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initRecy() {
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view,
                                       RecyclerView parent, RecyclerView.State state) {
                int index = parent.getChildAdapterPosition(view);
                if (index == 0 && infos.get(index).isHeader) {
                    outRect.left = 0;
                    outRect.right = 0;
                    outRect.top = 0;
                    outRect.bottom = 0;
                } else {
                    int dp = Utils.dip2px(parent.getContext(), 15);
                    outRect.left = dp;
                    outRect.right = dp;
                    outRect.bottom = index + 1 == infos.size() ? dp : 0;
                    outRect.top = dp;
                }
            }
        });
    }

    private void initView() {
        setTitle(className);
        mRecyclerView = findViewById(R.id.mRecyclerView);
        noData = findViewById(R.id.noData);
        complete=findViewById(R.id.complete);
        complete.setVisibility(View.VISIBLE);
        complete.setText("补发作业");
        mSmartRefreshLayout = findViewById(R.id.smartRefreshLayout);
        ClassicsHeader headerView = new ClassicsHeader(this);
        ClassicsFooter footView = new ClassicsFooter(this);
        headerView.setBackgroundColor(Color.parseColor("#f8f8f8"));
        footView.setBackgroundColor(Color.parseColor("#f8f8f8"));
        mSmartRefreshLayout.setRefreshHeader(headerView);
        mSmartRefreshLayout.setRefreshFooter(footView);
    }


    private HomeWorkPublishInfo getPublishInfo(List<HomeWorkIM> imMessages, int status) {
        HomeWorkPublishInfo homeWorkPublishInfo = new HomeWorkPublishInfo();
        homeWorkPublishInfo.isHoomworkAbort = status == 1;
        List<String> imageUrls = new ArrayList<>();
        for (int i = 0; i < imMessages.size(); i++) {
            IMMessage message = imMessages.get(i);
            homeWorkPublishInfo.sessionId = (String) message.getRemoteExtension().get("sessionId");
            if (message.getMsgType() == MsgTypeEnum.text) {
                homeWorkPublishInfo.homeworkContent = message.getContent();
            } else if (message.getMsgType() == MsgTypeEnum.audio) {
                homeWorkPublishInfo.homeworkAudioUrl = ((AudioAttachment) message.getAttachment()).getUrl();
                homeWorkPublishInfo.homeworkAudioDuration = ((AudioAttachment) message.getAttachment()).getDuration();
            } else if (message.getMsgType() == MsgTypeEnum.image) {
                imageUrls.add(getImageUrl(message));
            }
        }
        homeWorkPublishInfo.homeworkImageUrls = imageUrls;
        return homeWorkPublishInfo;
    }

    private String getImageUrl(IMMessage imMessage) {
        FileAttachment msgAttachment = (FileAttachment) imMessage.getAttachment();
        String path = msgAttachment.getPath();
        String thumbPath = msgAttachment.getThumbPath();
        String url = msgAttachment.getUrl();
        if (!TextUtils.isEmpty(path)) {
            return path;
        } else if (!TextUtils.isEmpty(url)) {
            return url;
        }else if (!TextUtils.isEmpty(thumbPath)) {
            return thumbPath;
        }  else {
            return "";
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        requestData();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == GlobalConstant.REQUEST_CODE_HOMEWORK_DETAIL_ACTIVITY) {
                if (infos != null && mClickPosition != -1 && infos.size() > mClickPosition && mAdapter != null && data != null) {
                    HomeWorkStateItem info = (HomeWorkStateItem) infos.get(mClickPosition);
                    int status = data.getIntExtra(GlobalConstant.RESULT_CODE_CORRECT_HOMEWORK, info.getStatus());
                    if (status != info.getStatus()) {
                        info.setStatus(status);
                        mAdapter.notifyItemChanged(mClickPosition);
                    }
                }
                mClickPosition = -1;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MediaManager.release();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MediaManager.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MediaManager.resume();
    }

    @Override
    public void onRecordPosition(int position) {
        this.mClickPosition = position;
    }

    @Override
    public int getNotSubmitStudentNumber() {
        int number = studentTotalNumber - studentSubmitNumber;
        return number == studentTotalNumber ? -1 : number;
    }
}
